package com.hh.fudan.project_management;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.Inflater;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.hh.fudan.project_management.basic.Global;
import com.hh.fudan.project_management.bean.Deal;
import com.hh.fudan.project_management.bean.Shop;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StrikethroughSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class DetailActivity extends Activity {

	private View headerView;
	private TextView titleView;
	private ImageView imageView;
	private TextView priceView;
	private TextView originalPriceView;
	private TextView discountView;
	private TextView deadlineView;
	private TextView detailView;
	private TextView shopsLabelView;
	private ListView shopListView;
	private LayoutInflater inflater;
	private Button shareButton;

	private String buyUrl;
	private static final int THREAD_LOADIMAGE = 1;

	private Deal deal;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.arg1 == THREAD_LOADIMAGE) {
				if (msg.obj == null)
					imageView.setImageResource(R.drawable.default_detail_image);
				else
					imageView.setImageDrawable((Drawable) msg.obj);
			}
		}
	};
	private DeadlineUpdater deadlineUpdater;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.details_shops);

		

		inflater = LayoutInflater.from(this);
		headerView = inflater.inflate(R.layout.details, null);
		shareButton = (Button) headerView.findViewById(R.id.button2);
		titleView = (TextView) headerView.findViewById(R.id.detailTitleView);
		imageView = (ImageView) headerView.findViewById(R.id.detailImageView);
		priceView = (TextView) headerView.findViewById(R.id.detailPriceView);
		originalPriceView = (TextView) headerView
				.findViewById(R.id.detailOriginalPriceView);
		discountView = (TextView) headerView
				.findViewById(R.id.detailDiscountView);
		deadlineView = (TextView) headerView
				.findViewById(R.id.detailDeadlineView);
		detailView = (TextView) headerView.findViewById(R.id.detailDetailView);
		shopsLabelView = (TextView) headerView
				.findViewById(R.id.detailShopsLabelView);

		shopListView = (ListView) findViewById(R.id.shopListView);
		shopListView.addHeaderView(headerView);
		shopListView.setHeaderDividersEnabled(false);
		fillContent();
		shareButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				StringBuffer sb = new StringBuffer();
				sb.append("@一盒团 ");
				sb.append("【" + deal.getCityName() + "】:");
				sb.append(deal.getTitle() + "");

				if (sb.length() > 120) {
					sb = new StringBuffer(sb.substring(0, 120));
				}
				sb.append(deal.getDealUrl());

				Intent intent = new Intent(Intent.ACTION_SEND);
				intent.setType("text/plain");
				intent.putExtra(Intent.EXTRA_SUBJECT, "分享");

				intent.putExtra(Intent.EXTRA_TEXT, sb.toString());
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(Intent.createChooser(intent, getTitle()));
			}
		});
	}

	// when share button clicked
	public void shareClicked(View v) {

	}

	private void fillContent() {
		String oid = this.getIntent().getStringExtra("oid");
		deal = getDeal(oid);

		if (deal == null) {
			warn(getString(R.string.detail_error));
		} else {
			buyUrl = deal.getDealUrl();
			titleView.setText(deal.getTitle());
			priceView.setText(getString(R.string.detail_money_prefix)
					+ deal.getPrice());
			String originalPrice = getString(R.string.detail_money_prefix)
					+ deal.getDealValue();
			SpannableString ss = new SpannableString(originalPrice);
			ss.setSpan(new StrikethroughSpan(), 1, originalPrice.length(),
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			originalPriceView.setText(ss);
			discountView.setText(deal.getDiscountPercent()
					+ getString(R.string.detail_discount_suffix));
			deadlineUpdater = new DeadlineUpdater(deal.getEndTime());
			handler.post(deadlineUpdater);
			loadImage(deal.getLImageUrl());
			String[] tips = deal.getTips().split(";");
			String tip = "";
			for (String t : tips) {
				tip += t.trim() + ";\n";
			}
			detailView.setText(tip);

			List<Shop> shops = deal.getShops();
			if (shops.size() == 0) {
				shopsLabelView.setVisibility(View.GONE);
			} else {
				shopListView.setAdapter(new ShopsAdapter(this, shops));
			}
		}
	}

	private Deal getDeal(String oid) {
		Deal deal = null;
		try {
			URL url = new URL(Global.SERVER_URL_BASE + "?oid=" + oid);
			SAXBuilder builder = new SAXBuilder(false);
			Document doc = builder.build(url);
			Element root = doc.getRootElement();

			List<Element> list = root.getChildren();
			if (list.size() > 0) {
				Element e = list.get(0);
				deal = new Deal();
				deal.setOid(oid);
				deal.setWebsiteId(e.getChildText("websiteId"));
				deal.setTitle(e.getChildText("title"));
				deal.setDealUrl(e.getChildText("dealUrl"));
				deal.setSImageUrl(e.getChildText("sImageUrl"));
				deal.setMImageUrl(e.getChildText("mImageUrl"));
				deal.setLImageUrl(e.getChildText("lImageUrl"));
				deal.setCityName(e.getChildText("cityName"));
				deal.setCategory(e.getChildText("category"));
				deal.setTips(e.getChildText("tips"));
				deal.setPrice(e.getChildText("price"));
				deal.setDealValue(e.getChildText("dealValue"));
				deal.setDiscountPercent(e.getChildText("discountPercent"));
				deal.setStartTime(Long.parseLong(e.getChildText("startTime")));
				deal.setEndTime(Long.parseLong(e.getChildText("endTime")));

				List<Shop> shops = new ArrayList<Shop>();
				List<Element> shopsE = e.getChild("shops").getChildren("shop");
				for (Element s : shopsE) {
					Shop shop = new Shop();
					shop.setLatitude(Double.parseDouble(s
							.getChildText("latitude")));
					shop.setLongtitude(Double.parseDouble(s
							.getChildText("longtitude")));
					shop.setShopAddress(s.getChildText("shopAddress"));
					shop.setShopArea(s.getChildText("shopArea"));
					shop.setShopName(s.getChildText("shopName"));
					shop.setShopPhone(s.getChildText("shopPhone"));
					shop.setShopUrl(s.getChildText("shopUrl"));
					shops.add(shop);
				}
				deal.setShops(shops);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return deal;
	}

	public void onBuy(View v) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setData(Uri.parse(buyUrl));
		intent = Intent.createChooser(intent, null);
		startActivity(intent);
	}

	private void loadImage(final String url) {
		Thread thread = new Thread() {
			@Override
			public void run() {
				Message message = handler.obtainMessage();
				message.arg1 = THREAD_LOADIMAGE;
				try {
					message.obj = Drawable.createFromStream(
							new URL(url).openStream(), "image");
				} catch (Exception e) {
					message.obj = null;
				} finally {
					handler.sendMessage(message);
				}
			}
		};
		thread.start();
		thread = null;
	}

	private void warn(String message) {
		new AlertDialog.Builder(this)
				.setTitle(R.string.error)
				.setMessage(message)
				.setNegativeButton(R.string.confirm,
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialoginterface, int i) {
								finish();
							}
						}).show();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		handler.removeCallbacks(deadlineUpdater);
	}

	private class DeadlineUpdater implements Runnable {
		private long endTime;

		DeadlineUpdater(long endTime) {
			this.endTime = endTime;
		}

		@Override
		public void run() {
			String deadline;
			int seconds = (int) (endTime - new Date().getTime() / 1000);
			if (seconds > 0) {
				int minutes = seconds / 60;
				int second = seconds - minutes * 60;
				deadline = second + getString(R.string.second);
				if (minutes > 0) {
					int hours = minutes / 60;
					int minute = minutes - hours * 60;
					deadline = minute + getString(R.string.minute) + deadline;
					if (hours > 0) {
						int day = hours / 24;
						int hour = hours - day * 24;
						deadline = hour + getString(R.string.hour) + deadline;
						if (day > 0) {
							deadline = day + getString(R.string.day) + deadline;
						}
					}
				}
			} else
				deadline = getString(R.string.date_expired);
			deadlineView.setText(deadline);

			handler.postDelayed(this, 1000);
		}

	}

	private class ShopsAdapter extends BaseAdapter {
		private List<Shop> shops;
		private LayoutInflater inflater;

		ShopsAdapter(Context context, List<Shop> shops) {
			this.inflater = LayoutInflater.from(context);
			this.shops = shops;
		}

		@Override
		public int getCount() {
			return shops.size();
		}

		@Override
		public Object getItem(int position) {
			return shops.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null)
				convertView = inflater.inflate(R.layout.shop_item, null);
			Shop shop = shops.get(position);
			TextView nameView = (TextView) convertView
					.findViewById(R.id.shopNameView);
			nameView.setText(shop.getShopName());
			TextView phoneView = (TextView) convertView
					.findViewById(R.id.shopPhoneView);
			phoneView.setText(shop.getShopPhone());
			TextView addressView = (TextView) convertView
					.findViewById(R.id.shopAddressView);
			addressView.setText(shop.getShopAddress());
			final double latitude = shop.getLatitude();
			final double longtitude = shop.getLongtitude();
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(
							Intent.ACTION_VIEW,
							Uri.parse("http://ditu.google.cn/maps?hl=zh&mrt=loc&q="
									+ longtitude + "," + latitude));
					startActivity(intent);
				}

			});
			return convertView;
		}

	}

}
